const { getUserInfo } = require('../service/user_service')

//导入jwt
const jwt = require('jsonwebtoken');

const { userFormateError, userAlreadyExited, userRegister, userNotExist, userLoginError, invalidPassword } = require('../constant/error_type.js')
const bcrypt = require('bcryptjs/dist/bcrypt.js')
//用户相关的中间件
//验证用户密码是否为空中间件
const userVaildator = async (ctx, next) => {
    const { user_name, password } = ctx.request.body
    if (!user_name || !password) {
        ctx.app.emit('error', userFormateError, ctx)
        return
    }
    await next()
}

const userVerify = async (ctx, next) => {
    const { user_name } = ctx.request.body
    // if (await getUserInfo({ user_name })) {
    //     ctx.app.emit('error', userAlreadyExited, ctx)
    //     return
    // }
    try {
        const res = await getUserInfo({ user_name })
        if (res) {
            console.error('用户名已存在', { user_name })
            ctx.app.emit('error', userAlreadyExited, ctx)
            return
        }

    } catch (error) {
        console.error('获取用户信息失败', error);
        ctx.app.emit('error', userRegister, ctx)
        return
    }
    await next()
}

//密码盐值加密
const crpytPassword = async (ctx, next) => {
    const { password } = ctx.request.body
    const salt = bcrypt.genSaltSync(10);
    // hash保存的是 密文
    const hash = bcrypt.hashSync(password, salt)
    ctx.request.body.password = hash

    await next();
}


//用户登录校验
const loginVerify = async (ctx, next) => {
    const { user_name, password } = ctx.request.body
    //1判断用户是否存在(不存在则报错)

    try {
        const res = await getUserInfo({ user_name })
        if (!res) {
            console.error(`${user_name}用户名不存在`);
            ctx.app.emit('error', userNotExist, ctx)
            return
        }
        //2.校验密码
        if (!bcrypt.compareSync(password, res.password)) {
            ctx.app.emit('error', invalidPassword, ctx)
            return
        }
    }
    catch (error) {
        console.log(error);
        ctx.app.emit('error', userLoginError, ctx)
        return
    }
    //用户不存在




    await next();
}

module.exports = { userVaildator, userVerify, crpytPassword, loginVerify }